//
// Copyright (c) 2012 Alexey Ulyanov
//
// Author:
//      Alexey Ulyanov (ALULY)
//
// This module hold a pair pointer and size of object
// Also we can get information about memory usage in current time

#include "usageMemory.hh"

#include <boost/foreach.hpp>

#include <iostream>
#include <stdlib.h>

MemoryMonitor::MemoryMonitor()
                       :m_MemoryUse(0)
{
    // Empty
}

MemoryMonitor::~MemoryMonitor()
{
    // Empty
}

bool MemoryMonitor::Add(void* a_Pointer, size_t a_Size)
{
    if (a_Size == 0) {
        return false;
    }
    
    if (!m_Pointers.insert(std::make_pair(a_Pointer, a_Size)).second)
    {
        return false;
    }
    m_MemoryUse += a_Size;

    return true;
}

size_t MemoryMonitor::Find(void* a_Pointer)
{
    BOOST_FOREACH(pair_t it, m_Pointers){
        if (a_Pointer == it.first){
            return it.second;
        }
    }

    return 0;
}

bool MemoryMonitor::Update(void* a_Pointer, size_t a_Size)
{
    if (!Delete(a_Pointer))
    {
        return false;
    }
    Add(a_Pointer, a_Size);

    return true;
}

bool MemoryMonitor::Delete(void* a_Pointer)
{
    BOOST_FOREACH(pair_t it, m_Pointers){
        if (a_Pointer == it.first){
            m_MemoryUse -= it.second;
            m_Pointers.erase(it);
            return true;
        }
    }
    return false;
}

size_t MemoryMonitor::GetUsedMem() const
{
    return m_MemoryUse;
}

int main(int argc, const char** argv)
{
    MemoryMonitor mem;
    int i = 1;
    char ch = 'c';

    mem.Add(&ch, sizeof(ch));
    mem.Add(&i, sizeof(i));
    float y = 33;
    mem.Find(&ch);
    
    mem.Update(&i, sizeof(double));
    mem.Delete(&i);

    return 0;
}
